<template>
  <a-modal
    v-model:open="visible"
    title="兑换卡密升级会员"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirm-loading="loading"
    width="480px"
    :maskClosable="false"
    class="care-code-modal"
  >
    <template #title>
      <div class="modal-title">
        <GiftOutlined class="title-icon" />
        <span class="title-text">兑换卡密升级会员</span>
      </div>
    </template>

    <div class="modal-content">
      <!-- 当前会员状态 -->
      <div class="current-status glass">
        <div class="status-header">
          <h4>当前会员状态</h4>
        </div>
        <div class="status-content">
          <div class="user-info">
            <VipAvatar 
              :avatar="userInfo?.userAvatar || loginUserStore.loginUser?.userAvatar"
              :vip-level="userInfo?.vipLevel || 0"
              :user-name="userInfo?.userName || loginUserStore.loginUser?.userName"
              :size="50"
              :show-pendant="false"
            />
            <div class="user-details">
              <div class="user-name">{{ userInfo?.userName || loginUserStore.loginUser?.userName || '登录用户' }}</div>
              <div class="user-level">
                <a-tag 
                  v-if="userInfo?.vipLevel && userInfo.vipLevel > 0"
                  :color="userInfo.vipLevel === 1 ? 'gold' : 'purple'"
                >
                  {{ userInfo.vipLevel === 1 ? 'VIP会员' : 'SVIP会员' }}
                </a-tag>
                <span v-else class="normal-user">普通用户</span>
              </div>
              <div v-if="userInfo?.expireTime" class="expire-time">
                到期时间：{{ formatDate(userInfo.expireTime) }}
                <span v-if="isExpiringSoon()" class="expire-warning">即将到期</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 卡密输入 -->
      <div class="care-code-form">
        <a-form :model="form" layout="vertical" @finish="handleSubmit">
          <a-form-item 
            label="卡密" 
            name="careCode" 
            :rules="careCodeRules"
          >
            <a-input 
              v-model:value="form.careCode" 
              placeholder="请输入您的卡密"
              :maxlength="50"
              allow-clear
              class="care-code-input"
            >
              <template #prefix>
                <KeyOutlined class="input-icon" />
              </template>
            </a-input>
          </a-form-item>
        </a-form>
      </div>

      <!-- 会员权益预览 -->
      <div class="benefits-preview glass">
        <div class="preview-header">
          <h4>会员权益说明</h4>
        </div>
        <div class="benefits-grid">
          <div class="benefit-card vip-card">
            <div class="card-header">
              <CrownOutlined class="card-icon" />
              <span class="card-title">VIP会员</span>
            </div>
            <div class="benefit-list">
              <div class="benefit-item">
                <CheckOutlined class="benefit-icon" />
                <span>无限图片上传</span>
              </div>
              <div class="benefit-item">
                <CheckOutlined class="benefit-icon" />
                <span>私有空间 (3个)</span>
              </div>
              <div class="benefit-item">
                <CheckOutlined class="benefit-icon" />
                <span>高级搜索功能</span>
              </div>
              <div class="benefit-item">
                <CheckOutlined class="benefit-icon" />
                <span>专属客服支持</span>
              </div>
            </div>
          </div>

          <div class="benefit-card svip-card">
            <div class="card-header">
              <StarOutlined class="card-icon" />
              <span class="card-title">SVIP会员</span>
            </div>
            <div class="benefit-list">
              <div class="benefit-item">
                <CheckOutlined class="benefit-icon" />
                <span>VIP所有权益</span>
              </div>
              <div class="benefit-item">
                <CheckOutlined class="benefit-icon" />
                <span>私有空间 (无限)</span>
              </div>
              <div class="benefit-item">
                <CheckOutlined class="benefit-icon" />
                <span>AI图片生成</span>
              </div>
              <div class="benefit-item">
                <CheckOutlined class="benefit-icon" />
                <span>AI图片修复</span>
              </div>
              <div class="benefit-item">
                <CheckOutlined class="benefit-icon" />
                <span>优先处理权限</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 使用说明 -->
      <div class="usage-tips">
        <div class="tips-header">
          <InfoCircleOutlined class="tips-icon" />
          <span>使用说明</span>
        </div>
        <ul class="tips-list">
          <li>请确保卡密输入正确，区分大小写</li>
          <li>每个卡密只能使用一次，使用后立即生效</li>
          <li>不同类型卡密有效期不同：天卡(1天)、周卡(7天)、月卡(30天)、年卡(365天)、永久卡(100年)</li>
          <li>如果您已是会员，新卡密时间将在当前到期时间基础上延长</li>
          <li>如有问题请联系客服：703793464@qq.com</li>
        </ul>
      </div>
    </div>

    <template #footer>
      <div class="modal-footer">
        <a-button @click="handleCancel">取消</a-button>
        <a-button 
          type="primary" 
          :loading="loading"
          @click="handleSubmit"
          :disabled="!form.careCode?.trim()"
          class="submit-btn"
        >
          <template #icon>
            <GiftOutlined />
          </template>
          立即兑换
        </a-button>
      </div>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import {
  GiftOutlined,
  KeyOutlined,
  CrownOutlined,
  StarOutlined,
  CheckOutlined,
  InfoCircleOutlined
} from '@ant-design/icons-vue'
import { useCareCodeUsingPost } from '@/api/careCodeController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import VipAvatar from './VipAvatar.vue'

// Props
interface Props {
  open?: boolean
  userInfo?: API.UserInfoVO | null
}

const props = withDefaults(defineProps<Props>(), {
  open: false,
  userInfo: null
})

// Emits
const emit = defineEmits<{
  'update:open': [value: boolean]
  'success': [result: any]
}>()

// 状态管理
const loginUserStore = useLoginUserStore()

// 响应式数据
const loading = ref(false)
const form = reactive({
  careCode: ''
})

// 计算属性
const visible = computed({
  get: () => props.open,
  set: (value) => emit('update:open', value)
})

// 表单验证规则
const careCodeRules = [
  { required: true, message: '请输入卡密', trigger: 'blur' },
  { min: 6, max: 50, message: '卡密长度应在6-50个字符之间', trigger: 'blur' },
  { 
    pattern: /^[A-Za-z0-9\-_]+$/, 
    message: '卡密只能包含字母、数字、横线和下划线', 
    trigger: 'blur' 
  }
]

// 方法
const handleSubmit = async () => {
  if (!form.careCode?.trim()) {
    message.error('请输入卡密')
    return
  }

  if (!loginUserStore.loginUser?.userAccount) {
    message.error('用户未登录')
    return
  }

  loading.value = true
  try {
    const res = await useCareCodeUsingPost({
      careCode: form.careCode.trim(),
      userAccount: loginUserStore.loginUser.userAccount
    })

    if (res.data.code === 0) {
      message.success({
        content: '🎉 卡密兑换成功！会员权益已生效',
        duration: 3
      })
      
      // 重置表单
      form.careCode = ''
      
      // 关闭弹窗
      visible.value = false
      
      // 通知父组件成功
      emit('success', res.data.data)
      
      // 可以在这里添加成功动画或特效
      showSuccessEffect()
      
    } else {
      message.error(res.data.message || '卡密兑换失败')
    }
  } catch (error) {
    console.error('卡密兑换失败:', error)
    message.error('卡密兑换失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  form.careCode = ''
  visible.value = false
}

const showSuccessEffect = () => {
  // 这里可以添加成功特效，比如烟花动画
  const duration = 3000
  const colors = ['#ffd700', '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4']
  
  for (let i = 0; i < 30; i++) {
    setTimeout(() => {
      createConfetti(colors[Math.floor(Math.random() * colors.length)])
    }, i * 100)
  }
}

const createConfetti = (color: string) => {
  const confetti = document.createElement('div')
  confetti.style.cssText = `
    position: fixed;
    width: 10px;
    height: 10px;
    background: ${color};
    border-radius: 50%;
    top: 20%;
    left: ${Math.random() * 100}%;
    animation: confetti-fall 3s linear forwards;
    pointer-events: none;
    z-index: 9999;
  `
  
  document.body.appendChild(confetti)
  
  setTimeout(() => {
    document.body.removeChild(confetti)
  }, 3000)
}

const isExpiringSoon = () => {
  if (!props.userInfo?.expireTime) return false
  const expireTime = new Date(props.userInfo.expireTime)
  const now = new Date()
  const diffDays = Math.ceil((expireTime.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
  return diffDays <= 7 && diffDays > 0
}

const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 监听弹窗打开状态，重置表单
watch(visible, (newVal) => {
  if (!newVal) {
    form.careCode = ''
  }
})
</script>

<style scoped>
/* 添加全局动画样式 */
:global(@keyframes confetti-fall) {
  0% {
    transform: translateY(0) rotate(0deg);
    opacity: 1;
  }
  100% {
    transform: translateY(100vh) rotate(720deg);
    opacity: 0;
  }
}

.care-code-modal {
  /* 自定义弹窗样式 */
}

.modal-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
}

.title-icon {
  font-size: 20px;
  color: #6366f1;
}

.title-text {
  background: linear-gradient(45deg, #6366f1, #8b5cf6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.modal-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.glass {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 16px;
}

.dark .glass {
  background: rgba(30, 30, 30, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.current-status {
  margin-bottom: 4px;
}

.status-header h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  opacity: 0.8;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 4px;
}

.user-level {
  margin-bottom: 4px;
}

.normal-user {
  color: #666;
  font-size: 12px;
}

.expire-time {
  font-size: 12px;
  opacity: 0.7;
}

.expire-warning {
  color: #ff4d4f;
  font-weight: 600;
  margin-left: 8px;
}

.care-code-form {
  margin: 4px 0;
}

.care-code-input {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  height: 40px;
}

.input-icon {
  color: #6366f1;
}

.benefits-preview {
  margin: 4px 0;
}

.preview-header h4 {
  margin: 0 0 16px 0;
  font-size: 14px;
  font-weight: 600;
  opacity: 0.8;
}

.benefits-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.benefit-card {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 12px;
  transition: all 0.3s ease;
}

.benefit-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.vip-card {
  border-color: rgba(255, 215, 0, 0.3);
}

.svip-card {
  border-color: rgba(139, 92, 246, 0.3);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 8px;
  font-weight: 600;
  font-size: 12px;
}

.vip-card .card-icon {
  color: #ffd700;
}

.svip-card .card-icon {
  color: #8b5cf6;
}

.benefit-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.benefit-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 11px;
  opacity: 0.9;
}

.benefit-icon {
  color: #52c41a;
  font-size: 10px;
  flex-shrink: 0;
}

.usage-tips {
  background: rgba(99, 102, 241, 0.1);
  border: 1px solid rgba(99, 102, 241, 0.2);
  border-radius: 8px;
  padding: 12px;
}

.tips-header {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 8px;
  font-size: 12px;
  font-weight: 600;
  color: #6366f1;
}

.tips-icon {
  font-size: 14px;
}

.tips-list {
  margin: 0;
  padding-left: 16px;
  list-style: none;
}

.tips-list li {
  font-size: 11px;
  line-height: 1.5;
  margin-bottom: 4px;
  opacity: 0.8;
  position: relative;
}

.tips-list li:before {
  content: '•';
  color: #6366f1;
  position: absolute;
  left: -12px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 8px;
}

.submit-btn {
  background: linear-gradient(45deg, #6366f1, #8b5cf6);
  border: none;
  border-radius: 6px;
  font-weight: 600;
  height: 36px;
  min-width: 100px;
}

.submit-btn:hover {
  background: linear-gradient(45deg, #5b5be6, #7c3aed);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .benefits-grid {
    grid-template-columns: 1fr;
  }
  
  .user-info {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .modal-content {
    gap: 16px;
  }
  
  .glass {
    padding: 12px;
  }
}

/* 深色模式特殊样式 */
.dark .benefit-card {
  background: rgba(40, 40, 40, 0.6);
  border-color: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.dark .usage-tips {
  background: rgba(99, 102, 241, 0.15);
  border-color: rgba(99, 102, 241, 0.3);
  color: #ffffff;
}

.dark .expire-warning {
  color: #ff7875;
}

.dark .current-status {
  color: #ffffff;
}

.dark .user-name {
  color: #ffffff;
}

.dark .normal-user {
  color: rgba(255, 255, 255, 0.6);
}

.dark .expire-time {
  color: rgba(255, 255, 255, 0.7);
}

.dark .status-header h4,
.dark .preview-header h4 {
  color: rgba(255, 255, 255, 0.8);
}

.dark .tips-header {
  color: #8b92ff;
}

.dark .tips-list li {
  color: rgba(255, 255, 255, 0.8);
}

.dark .tips-list li:before {
  color: #8b92ff;
}

.dark .glass {
  background: rgba(40, 40, 40, 0.8);
  border-color: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

/* 动画增强 */
.care-code-modal :deep(.ant-modal-content) {
  border-radius: 16px;
  overflow: hidden;
  backdrop-filter: blur(20px);
}

.care-code-modal :deep(.ant-modal-header) {
  background: rgba(255, 255, 255, 0.1);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.dark .care-code-modal :deep(.ant-modal-content) {
  background: rgba(30, 30, 30, 0.95);
}

.dark .care-code-modal :deep(.ant-modal-header) {
  background: rgba(40, 40, 40, 0.8);
}

/* 黑色模式表单元素适配 */
.dark .care-code-modal :deep(.ant-form-item-label > label) {
  color: #ffffff;
}

.dark .care-code-modal :deep(.ant-input) {
  background: rgba(40, 40, 40, 0.8);
  border-color: rgba(255, 255, 255, 0.2);
  color: #ffffff;
}

.dark .care-code-modal :deep(.ant-input:focus) {
  border-color: #6366f1;
  box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
}

.dark .care-code-modal :deep(.ant-input::placeholder) {
  color: rgba(255, 255, 255, 0.4);
}

.dark .care-code-modal :deep(.ant-btn:not(.ant-btn-primary)) {
  background: rgba(40, 40, 40, 0.8);
  border-color: rgba(255, 255, 255, 0.2);
  color: #ffffff;
}

.dark .care-code-modal :deep(.ant-btn:not(.ant-btn-primary):hover) {
  background: rgba(60, 60, 60, 0.8);
  border-color: rgba(255, 255, 255, 0.3);
}

.dark .input-icon {
  color: #8b92ff;
}
</style>
